package com.sencorsta.ids.core.application.proxy.handler;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.core.application.proxy.ProxyClient;
import com.sencorsta.ids.core.configure.TypeProtocol;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessage;
import com.sencorsta.ids.core.tcp.opensocket.OpenServerBootstrap;
import com.sencorsta.ids.core.tcp.opensocket.OpenUser;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessageHandler;
import io.netty.channel.Channel;

@ClientEvent("Broadcast")
public class Broadcast extends RpcMessageHandler {

	@Override
	public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {

		String subscribeId=json.getString("subscribeId");
		String method=json.getString("method");
		Short serializeType=json.getShort("serializeType");
		byte[] dataJ=json.getBytes("data");

		Out.debug("开始广播","subscribeId:",subscribeId);
		Out.debug("开始广播","用户数量:",OpenServerBootstrap.getInstance().users.values().size());
		for (OpenUser user:OpenServerBootstrap.getInstance().users.values()) {
			if (user.Subscribes.contains(subscribeId)){
				Out.debug("开始广播","匹配到用户:",user.userId);
				OpenMessage message = new OpenMessage();
				message.method = method;
				message.serializeType = serializeType;
				message.data = dataJ;
				message.header.type = TypeProtocol.TYPE_RES;
				message.channel=user.channel;
				user.sendMsg(message);
			}
		}

		return  empty();
	}

}
